from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from .models import OrderGoods,OrderInfo,Addr,Payment
from user.models import User
from sku.models import Good
from sku.serializers import GoodSer
from .serializers import OrderSer,InfoSer,AddSer,PaySer
# Create your views here.
class GetInfoView(APIView):
    def get(self,request):
        page = int(request.query_params.get('page'))
        size = int(request.query_params.get('size'))
        data = OrderInfo.objects.all()[((page-1)*size):(page*size)]
        ser = InfoSer(data,many=True)
        return Response({'data':ser.data,'count':OrderInfo.objects.all().count()})

class GetOneOrder(APIView):
    def get(self,request,id):
        try:
            # user_data = User.objects.get(id=data.user_id)
            # 订单信息
            data = OrderInfo.objects.get(order_id=id)
            ser = InfoSer(data)
            # 通过订单获取指定的商品
            goods_data = OrderGoods.objects.filter(order_id=data.order_id)
            order_goods_ser = OrderSer(goods_data,many=True)
            order_goods_list = []
            for i in order_goods_ser.data:
                i["sku"] = GoodSer(Good.objects.filter(id=i.get("sku")).first()).data
                order_goods_list.append(i)
            my_data = ser.data
            my_data["skus"] = order_goods_list
            return Response({'list': my_data, 'code': 200})
            # skus = [
            #     {
            #         'sku':{
            #             'image_default': goods.image_default,
            #             'name': goods.name,
            #         },
            #         'count': goods_data.count,
            #         'price': goods_data.price,
            #     }
            # ]
            # order_list = {
                # 'order_id':id,
                # 'created_time':data.created_time,
                # 'user_name':user_data.username,
                # 'total_count':data.total_count,
                # 'total_amount':data.total_amount,
                # 'freight':data.freight,
                # 'pay_method':data.pay_method,
                # 'status':data.get_status_display(),
                # 'skus':skus
            # }
            # return Response({'list':order_list,'code':200})
        except Exception as e:
            print(e)
            return Response({'msg':'获取失败','code':204})

    def put(self,request,id):
        status_id = request.data.get('status')
        try:
            data = OrderInfo.objects.get(order_id=id)
            data.status = status_id
            data.save()
            return Response({'msg':'修改状态成功','code':200})
        except Exception as e:
            print(e)
            return Response({'msg':'修改状态失败','code':204})
